package com.mylogger;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ArrayBlockingQueue;

public class AsyncFileAppender implements Runnable{
	
	private final int QUEUE_SIZE = 100;
	
	private PrintWriter pw;
	private Thread adapterThread;
	private final static String FILE_NAME = "logfile.log";
	
	private static volatile AsyncFileAppender myInstance = null;
	private static DateFormat dateFormatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.UK); ;
	
	private ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(QUEUE_SIZE);
	
    private AsyncFileAppender(){
    	
    	try {
    		pw  = new PrintWriter(new FileOutputStream(FILE_NAME, true));
    	} catch (FileNotFoundException e) {
    		throw new LogFileNotFoundException(FILE_NAME + " not found");
    	}
    	
		adapterThread = new Thread(this);
		adapterThread.setDaemon(true);
		adapterThread.start();
    	
    }

    public static AsyncFileAppender getInstance(){
    	if ( myInstance == null ){
    		synchronized(AsyncFileAppender.class){
    			myInstance = new AsyncFileAppender();
    		}
    	}
    	return myInstance;
    }
    
    public void addMessage(String message){
    	try {
			queue.put(message);
		} catch (InterruptedException e) {
			shutDown();
		}
    }
    
    
	@Override
	public void run() {
		while (!Thread.currentThread().isInterrupted()){
			String msg;
			try {
				msg = queue.take();
			} catch (InterruptedException e) {
				shutDown();
				break;
			}
			pw.println(msg);
			pw.flush();
		}
		
	}
	
	public static String getCurrentDate(){
		
		Date today = new Date();
		return dateFormatter.format(today);
	}

	
	private void shutDown(){
		pw.close();
	}
}